package com.dream.service.abs;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.dream.pojo.Imgjson;
import com.dream.service.able.Upload_able;

/*
 * 上传图片抽象基类
 */
public abstract class AbsUpload  implements Upload_able<Imgjson> {

	/*
	 * (上传图片)
	 * @see com.dream.service.able.Upload#upload(org.springframework.web.multipart.MultipartFile, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public Imgjson upload(MultipartFile file,HttpServletRequest request) {
		Imgjson imgjson=new Imgjson();
		if(file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
			String origName=file.getOriginalFilename();//得到文件名
			String extendsName=origName.substring(origName.lastIndexOf("."));//得到文件后缀BMP、JPG、JPEG、PNG、GIF。 BMP
			if(extendsName.equals(".bmp")||extendsName.equals(".jpg")||extendsName.equals(".jpeg")||extendsName.equals(".png")||extendsName.equals(".gif")){
				//SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");//设置日期格式  
				String randanddate=UUID.randomUUID().toString(); // new Date()为获取当前系统时间  
				//保存路径
				String filename=this.getClass().getClassLoader().getResource("").getPath()+"../file/images/dreamimg/"+randanddate+extendsName;
				File uploadFile=new File(filename);
				try {
					file.transferTo(uploadFile);
					imgjson.setCode(0);//0表示没有错误
					imgjson.setMsg("提示");
					String [] Data={request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/file/images/dreamimg/"+randanddate+extendsName};
					imgjson.setData(Data);
					System.err.println("保存图片了");
					return imgjson;
				} catch (IllegalStateException | IOException e) {
					System.out.println(e.getMessage());
					imgjson.setCode(1);//1文件上传异常
					return imgjson;
				}
			}else{
				imgjson.setCode(2);//2用户上传的文件格式不正确
			}
		}else{
			imgjson.setCode(3);//3用户没有上传文件
		}
		return imgjson;
	}

}
